package com.hwl.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwl.statistics.feign.UcenterMemberService;
import com.hwl.statistics.mapper.DailyMapper;
import com.hwl.statistics.pojo.Daily;
import com.hwl.statistics.service.DailyService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author long
 * @since 2021-10-10
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {

    @Resource
    private UcenterMemberService ucenterMemberService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createStatisticsByDay(String day) {
        //如果当日统计信息已存在，则删除记录
        baseMapper.delete(new QueryWrapper<Daily>().eq("date_calculated", day));

        Integer registerNum = (Integer) ucenterMemberService.countRegisterNum(day).getData();
        Daily daily = new Daily()
                .setRegisterNum(registerNum + RandomUtils.nextInt(50, 100)) //注册人数
                .setVideoViewNum(RandomUtils.nextInt(100, 200)) //模拟
                .setLoginNum(RandomUtils.nextInt(100, 200))
                .setCourseNum(RandomUtils.nextInt(10, 20))
                .setDateCalculated(day); //统计日期

        return baseMapper.insert(daily) > 0;
    }

    @Override
    public Map<String, Object> getChartData(String begin, String end) {
        List<Daily> dailyList = baseMapper.selectList(new QueryWrapper<Daily>().between("date_calculated", begin, end));
        List<String> dateList = dailyList.stream().map(Daily::getDateCalculated).collect(Collectors.toList());

        List<Integer> loginList = dailyList.stream().map(Daily::getLoginNum).collect(Collectors.toList());
        List<Integer> registerList = dailyList.stream().map(Daily::getRegisterNum).collect(Collectors.toList());
        List<Integer> videoViewList = dailyList.stream().map(Daily::getVideoViewNum).collect(Collectors.toList());
        List<Integer> courseList = dailyList.stream().map(Daily::getCourseNum).collect(Collectors.toList());

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("dateList", dateList);
        resMap.put("loginNum", loginList);
        resMap.put("registerNum", registerList);
        resMap.put("videoViewNum", videoViewList);
        resMap.put("courseNum", courseList);

        return resMap;
    }
}
